'use strict';

module.exports = core

const semver = require('semver') // 版本比对
const colors = require('colors/safe')
const userHome = require('user-home')
// 4.0 用的是 commonjs  5.0 用的是esm
const pathExists = require('path-exists').sync
const commander = require('commander')

const pkg = require('../package.json')
const log = require('@baseh-cli-dev/log')
const init = require('@baseh-cli-dev/init')
const exec = require('@baseh-cli-dev/exec')
const constant = require('./const')
const path = require('path')

let config

const program = new commander.Command()  // 实例化脚手架对象

async function core () {
  // TODO
  // console.log('exec core')
  try {
    await prepare()
    registerCommand()
  } catch(e) {
    log.error(e)
  }
}

async function prepare () {
  checkPkgVersion()
  // checkNodeVersion()
  checkRoot()
  checkUserHome()
  // checkInputArgs()
  // log.verbose('debug', 'test debug log')
  checkEnv()
  await checkGlobalUpdate()
}

// 命令注册
function registerCommand () {
  program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command> [options]')
    .version(pkg.version)
    .option('-d, --debug', '是否开启调试模式', false)
    .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径', '')

  program
    .command('init [projectName]')
    .option('-f, --force', '是否强制初始化项目')
    .action(exec)

  // 开启debug模式
  program.on('option:debug', function () {
    if (program.debug) {
      process.env.LOG_LEVEL = 'verbose'
    } else {
      process.env.LOG_LEVEL = 'info'
    }

    log.level = process.env.LOG_LEVEL
  })

  // 指定targetpath
  program.on('option:targetPath', function () {
    process.env.CLI_TARGET_PATH = program.targetPath
  })

  program.on('command:*', function (obj) {
    const availableCommands = program.commands.map(cmd => cmd.name())
    console.log(colors.red('未知的命令:' + obj[0]))
    if (availableCommands.length > 0) {
      console.log(colors.red('可用的命令:' + availableCommands.join(',')))
    }
  })

  program.parse(process.argv)
  if (program.args && program.args.length < 1) {
    program.outputHelp();

    console.log()
  }
}

async function checkGlobalUpdate () {
  // 获取当前版本号t 默认名
  const currentVersion = pkg.version
  const npmName = pkg.name
  // 调用npm api 获取所有版本对比
  const {getNpmSemverVersion} = require('@baseh-cli-dev/get-npm-info')
  const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
  console.log(lastVersion)
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn('更新提示', colors.yellow(`请手动更新${npmName}, 当前版本${currentVersion}, 最新版本${lastVersion}
更新命令： npm install -g ${npmName}`))
  }
}

// 检查环境变量 dotenv
function checkEnv () {
  const dotenv = require('dotenv')
  const dotenvPath = path.resolve(userHome, '.env')
  if (pathExists(dotenvPath)) {
    dotenv.config({
      path: dotenvPath
    })
  }

  // 不存在生成默认
  createDefaultConfig()
}

function createDefaultConfig () {
  const cliConfig = {
    home: userHome
  }
  if (process.env.CLI_HOME) {
    cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME)
  } else {
    cliConfig['cliHome'] = path.join(userHome, constant.DEFAULT_CLI_HOME)
  }

  process.env.CLI_HOME_PATH = cliConfig['cliHome']
  // return cliConfig
}

// minimist
function checkInputArgs () {
  const minimist = require('minimist')
  const args = minimist(process.argv.slice(2))
  if (args.debug) {
    process.env.LOG_LEVEL = 'verbose'
  } else {
    process.env.LOG_LEVEL = 'info'
  }
  log.level = process.env.LOG_LEVEL
}

function checkUserHome () {
  console.log(userHome)
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red('当前登录用户主目录不存在'))
  }
}

// 检查root 降级 root-check
// 1.0 用的是 commonjs  2.0 用的是esm
function checkRoot () {
  const checkRoot = require('root-check')
  checkRoot()
  // checkRoot()
  // console.log(process.getuid())
}

function checkNodeVersion () {
  // 获取当前node版本号
  const currentVersion = process.version
  // 比对最低版本号
  const lowestVersion = constant.LOWEST_NODE_VERSION
  // semver
  if (!semver.gte(currentVersion, lowestVersion)) {
    throw new Error(colors.red(`baseh-cli 需要安装 v${lowestVersion} 以上版本Node.js`))
  }
}

// 检查版本号
function checkPkgVersion () {
  // console.log(pkg.version)
  // log.success('test', 'success...')
  log.notice('cli', pkg.version)
}